import sun.java2d.pipe.OutlineTextRenderer;

import java.util.*;

/**
 * @author 03010570
 * @date 2020/07/13
 * describe:    LeetCode : 349、两个数组的交集  https://leetcode-cn.com/problems/intersection-of-two-arrays/
 */
public class LeetCode_349 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        int[] intersection = intersection(nums1, nums2);
        for (int i : intersection) {
            System.out.print(i + " , ");
        }
        int[] nums3 = {4, 9, 5};
        int[] nums4 = {9, 4, 9, 8, 4};
        int[] intersection2 = intersection(nums3, nums4);
        for (int i : intersection2) {
            System.out.print(i + " , ");
        }
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }
        Set<Integer> set2 = new HashSet<>();
        for (int i : nums2) {
            set2.add(i);
        }
        set1.retainAll(set2);
        int[] res = new int[set1.size()];
        int index = 0;
        for (Integer integer : set1) {
            res[index++] = integer;
        }
        return res;
    }


    /**
     * Method 1:
     * 方法不太行
     * 使用 map 查找 子集，
     * 时间复杂度 ： O(M+N+K)
     * 空间复杂度 ： O(2N)   HashMap 、 ArrayList
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersection2(int[] nums1, int[] nums2) {
        if (nums1.length == 0 || nums2.length == 0) {
            return new int[0];
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], 0);
        }
        List<Integer> list = new ArrayList<>();
        for (int j = 0; j < nums2.length; j++) {
            if (map.get(nums2[j]) != null && map.get(nums2[j]) == 0) {
                list.add(nums2[j]);
                map.put(nums2[j], map.get(nums2[j]) + 1);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
